package com.wsfPro.security.config;

import com.wsfPro.core.system.SysMenuService;
import com.wsfPro.entities.system.SysMenuEntity;
import com.wsfPro.entities.system.SysRoleEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/** 本类处理请求的url资源需拥有的权限 */
@Component
public class UrlFilterInvocationSecurityMetadataSource
    implements FilterInvocationSecurityMetadataSource {
  @Autowired SysMenuService menuService;

  /**
   * AccessDecisionManager将处理getAttributes(Object o)方法返回的角色集合名是否与当前登录者所拥有的角色一致
   *
   * @param o
   */
  @Override
  public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    FilterInvocation filterInvocation = (FilterInvocation) o;
    String param = "GET";
    String requestUrl = filterInvocation.getRequestUrl();
    if (filterInvocation.getHttpRequest().getMethod().equals(param)) {
      param = "?";
      int indexGet = requestUrl.lastIndexOf(param);
      if (indexGet != -1) {
        requestUrl = requestUrl.substring(0, indexGet);
      }
    }
    param = "/login_p";
    if (param.equals(requestUrl)) {
      return null;
    }
    param = "/";
    String[] requestUrlArray = requestUrl.split(param);
    if (requestUrlArray.length == 4) {
      String urlId = requestUrlArray[2];
      String matchUrl = requestUrlArray[1] + requestUrlArray[3];

      SysMenuEntity menu = menuService.findMenuRoleById(urlId);
      if (menu != null) {
        //            url-matchUrl-
        String[] menuUrlArray = menu.getUrl().split(param);
        String menuUrl = menuUrlArray[0] + menuUrlArray[1];
        if (matchUrl.equals(menuUrl)) {
          List<SysRoleEntity> roles = menu.getSysRoleList();
          if (roles != null) {
            //      该url资源菜单对应的所有角色权限
            int size = roles.size();
            String[] values = new String[size];
            for (int i = 0; i < size; i++) {
              values[i] = roles.get(i).getName();
            }
            // 返回菜单所有的角色权限名给后续校验当前登陆实体是否有对应的权限
            return SecurityConfig.createList(values);
          }
        }
      }
    }
    param = "ROLE_LOGIN";
    // 没有匹配上的url资源，都是登录访问
    return SecurityConfig.createList(param);
  }

  @Override
  public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return FilterInvocation.class.isAssignableFrom(aClass);
  }
}
